package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zhanyan/pac/util"
	"zhanyan/service/user_service"
)

// Login
// @Summary      登录
// @Description  登录
// @Tags         login
// @Accept       json
// @Produce      json
// @Param        auth   json      int  true  "名字"
// @Success      200  {object}  map[string]interface{}
// @Router       /login [post]
func Login(c *gin.Context) {
	user := user_service.User{}
	if c.ShouldBindJSON(&user) != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusNoContent,
			"msg":  "参数错误",
		})
		return
	}
	if user.IsExist() && user.Username != "" && user.Password != "" {
		u := &user_service.User{Username: user.Username}
		err := u.GetByName()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusNoContent,
				"msg":  "后端程序错误",
			})
		}
		info := &util.Auth{}
		err = util.Transfer(u, info)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": http.StatusNoContent,
				"msg":  "解析出错",
			})
		}
		tokenString, _ := util.GenerateToken(*info)
		c.JSON(http.StatusOK, gin.H{
			"code":  http.StatusOK,
			"token": tokenString,
			"msg":   "登录成功",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusNoContent,
		"msg":  "登录失败",
	})
}
